package cn.ruituo.dao;

import cn.ruituo.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author oldliu
 * @since 1.0
 */
public class BankDao {
    /**
     * 事务：ACID
     */
    public int transfer(String from,String to,float money){
        String sql1="update bank set balance=balance-? where no=?";
        String sql2="update bank set balance=balance+? where no=?";


            Connection con = null;
            PreparedStatement ps = null,ps2=null;
            ResultSet rs = null;
            int total = 0;
            try {
                con = DBUtil.getConnection();
                //关闭自动提交
                con.setAutoCommit(false);
                ps = con.prepareStatement(sql1);
                ps.setFloat(1,money);
                ps.setString(2,from);
                int r1=ps.executeUpdate();
                //
                ps2 = con.prepareStatement(sql2);
                ps2.setFloat(1,money);
                ps2.setString(2,to);
                int r2=ps2.executeUpdate();
                if(r1>0&&r2>0)
                {
                    con.commit();
                    return 1;
                }
                else
                    con.rollback();
            } catch (SQLException e) {
                try {
                    con.rollback();//异常，无条件回滚
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                DBUtil.handleException(e);
            } finally {
                DBUtil.close(ps);
                DBUtil.close(ps2);
                DBUtil.close(con);
            }

        return 0;
    }

    public static void main(String[] args) {
        BankDao dao=new BankDao();
        int result=dao.transfer("liuqi","wurui",900);
        System.out.println(result);
    }
}
